package com.njupt.swg.threadstudyjimin.item04.atomic;

import com.njupt.swg.threadstudyjimin.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

@Slf4j
@ThreadSafe
public class AtomicIntegerFieldUpdaterTest {
    //表示更新AtomicIntegerFieldUpdaterTest这个类的count字段
    private static AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> updater =
            AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class,"count");

    //不能是static,必须是volatile
    public volatile int count = 100;

    public int getCount(){
        return count;
    }

    public static void main(String[] args) {
        AtomicIntegerFieldUpdaterTest example = new AtomicIntegerFieldUpdaterTest();

        if(updater.compareAndSet(example,100,200)){
            log.info("update success 1:{}",example.getCount());
        }

        if(updater.compareAndSet(example,100,200)){
            log.info("update success 2:{}",example.getCount());
        }else {
            log.error("update fail");
        }
    }
}
